<?php

/**
 * docreateaccount.php
 * @package adServer
 * @filesource
 */

/*	Close the backdoor	*/
$curPage = strtoupper($_SERVER['PHP_SELF']);
if (isset($curPage) && strpos($curPage, 'INDEX.PHP') === false)
    header('Location:./index.php');

require_once (CLASS_PATH . 'template.class.php');


/*	Check if there is a form submitted	*/
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['password2'])) {
    if ($session->loggedIn == true) {
        /* Validate new account */
        $error = '';
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);
        $password2 = mysql_real_escape_string($_POST['password2']);
        $qry = str_replace('%%USER%%', $username, SQL_USER_EXISTS);
        if ($session->dbHandle->get_result_bool($qry) == true)
            $error .= 'The username already exists<br/>';
        if (strlen($username) < 3 || strlen($username) > 20)
            $error .=
                'The username should be minimum 3 characters and maximum 20 characters<br/>';
        if ($password != $password2)
            $error .=
                "The password and the verification password doesn't match<br/>";
        if (strlen($password) < 5 || strlen($password) > 20)
            $error .=
                'The password should be minimum 5 characters and maximum 20 characters<br/>';
        if ($error == '')
            $session->createAccount($username, $password);

        $session->closeSession();
        $session->userLogin($username, $password);

    } else {
        $error = 'Illegal operation, please try again';
    }

    if ($error == '' && $session->userLogin($username, $password) == true) {
        header('Location:./index.php?action=display');
    }

    /* Load the side menu */
    $sideMenu = '';
    if ($session->loggedIn) {
        $sideMenu = file_get_contents(TEMPLATE_PATH . 'sideMenu.tpl');
    }
    $sideMenu = file_get_contents(TEMPLATE_PATH . 'sideMenu.tpl');

    /*	load the page header	*/
    $header = new template(TEMPLATE_PATH . 'header.tpl');
    $header->replace('&&SIDEMENU&&', $sideMenu);
    $header->replace('&&STYLE&&', $session->loggedIn ? "style='display:block;'" :
        "");
    $header->replace('&&USER&&', $session->username);

    /*	Load the page content	*/
    $pageContent = new template(TEMPLATE_PATH . 'createaccount.tpl');

    /*	Remove the error container	*/
    $pageContent->replace('&&ERRMSG&&', $error);

    /*	Echo the page	*/
    echo $header->templateHtml;
    echo $pageContent->templateHtml;


}

?>